package com.java.controller;

import com.java.bean.*;
import com.java.mvc.ResponseBody;
import com.java.service.CourierService;
import com.java.service.UserService;
import com.java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserController{

    private CourierService courierService = new CourierService();
    private UserService userService = new UserService();

    @ResponseBody("/user/console.do")
    public String console(HttpServletRequest request, HttpServletResponse response){
        List<Map<String, Integer>> data = UserService.console();
        Message msg = new Message();
        if(data.size() == 0){
            msg.setStatus(-1);
        }else {
            msg.setStatus(0);
        }
        msg.setData(data);
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/user/list.do")
    public String list(HttpServletRequest request, HttpServletResponse response){
        //1.    获取查询数据的起始索引值
        int offset = Integer.parseInt(request.getParameter("offset"));
        //2.    获取当前页要查询的数据量
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        //3.    进行查询
        List<User> list = UserService.findAll(true, offset, pageNumber);
        List<BootStrapTableUser> list2 = new ArrayList<>();
        for(User e:list){
            String createTime = DateFormatUtil.format(e.getCreateTime());
            String loginTime = DateFormatUtil.format(e.getLoginTime());
            //BootStrapTableUser(int id, String name, String phone, String password, String createTime, String loginTime)
            BootStrapTableUser e2 = new BootStrapTableUser(e.getId(),e.getName(),e.getPhone(),e.getPassword(),createTime,loginTime);
            list2.add(e2);
        }
        List<Map<String, Integer>> console = UserService.console();
        Integer total = console.get(0).get("user_size");
        //4.    将集合封装为 bootstrap-table识别的格式
        ResultData<BootStrapTableUser> data = new ResultData<>();
        data.setRows(list2);
        data.setTotal(total);
        String json = JSONUtil.toJSON(data);
        return json;
    }

    @ResponseBody("/user/find.do")
    public String find(HttpServletRequest request,HttpServletResponse response){
        String phone = request.getParameter("phone");
        User e = UserService.findByPhone(phone);
        Message msg = new Message();
        if(e == null){
            msg.setStatus(-1);
            msg.setResult("手机号不存在");
        }else{
            msg.setStatus(0);
            msg.setResult("查询成功");
            msg.setData(e);
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/user/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String password = request.getParameter("password");
        //User(int id, String name, String phone, String password)
        User e = new User(name,phone,password);
        boolean flag = UserService.insert(e);
        Message msg = new Message();
        if(flag){
            //录入成功
            msg.setStatus(0);
            msg.setResult("用户录入成功!");
        }else{
            //录入失败
            msg.setStatus(-1);
            msg.setResult("用户录入失败!");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/user/update.do")
    public String update(HttpServletRequest request,HttpServletResponse response){
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String oldphone = request.getParameter("oldphone");
        User newUser = new User();
        newUser.setPassword(password);
        newUser.setName(name);
        newUser.setPhone(phone);
        boolean flag = UserService.update(oldphone, newUser);
        Message msg = new Message();
        if(flag){
            msg.setStatus(0);
            msg.setResult("修改成功");
        }else{
            msg.setStatus(-1);
            msg.setResult("修改失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/user/delete.do")
    public String delete(HttpServletRequest request,HttpServletResponse response){
        String phone = request.getParameter("phone");
        boolean flag = UserService.delete(phone);
        Message msg = new Message();
        if(flag){
            msg.setStatus(0);
            msg.setResult("删除成功");
        }else{
            msg.setStatus(-1);
            msg.setResult("删除失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/wx/loginSms.do")
    public String sendSms(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        String code = RandomUtil.getCode() + "";
        //调用发送短信接口（假）
        Boolean flag = SMSUtil.loginSMS(userPhone, code);
        Message msg = new Message();
        if(flag) {
            msg.setStatus(0);
            msg.setResult("验证码发送成功");
            msg.setData(code);
        } else {
            msg.setStatus(1);
            msg.setResult("验证码发送失败");
        }
        //保存手机号对应验证码到session中
        UserUtil.setLoginSms(request.getSession(), userPhone, code);
        return JSONUtil.toJSON(msg);
    }

    /**
     * 微信端用户登录
     * @param request
     * @return
     */
    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userPhone = request.getParameter("userPhone");
        String userCode = request.getParameter("code");
        String code = UserUtil.getLoginSms(request.getSession(), userPhone);
        Message msg = new Message();

        User user = new User();
        user.setPhone(userPhone);

        if(code == null) {
            //手机号未发送短信
            msg.setStatus(-1);
            msg.setResult("手机号码未获取短信");
        } else if(code.equals(userCode)) {
            //查询用户信息
            Courier courier = courierService.findByNumber(userPhone);
            if(courier != null) {
                //快递员返回1
                msg.setStatus(1);
                user.setFlag(0);
            } else {
                //判断是否是用户，非用户进行自动注册
                if(userService.findByPhone(userPhone) == null) {
                    if(userService.insertByPhone(userPhone)) {
                        msg.setStatus(2);
                        user.setFlag(1);
                    }
                } else {
                    //用户返回0
                    msg.setStatus(0);
                    user.setFlag(1);
                }
            }
            UserUtil.setWxUser(request.getSession(), user);
        } else {
            msg.setStatus(-2);
            msg.setResult("验证码不一致");
        }

        return JSONUtil.toJSON(msg);
    }

    /**
     * 微信端用户注销
     * @param request
     * @return
     */
    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        // 1. 销毁session
        request.getSession().invalidate();
        // 2. 给客户端回复消息
        return JSONUtil.toJSON(new Message(0, "用户已注销"));
    }

    /**
     * 微信端获取当前登录用户信息
     * @param request
     * @return
     */
    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response) {
        Message msg = new Message();
        User wxUser = UserUtil.getWxUser(request.getSession());
        if(wxUser.isUser()) {
            //用户
            msg.setStatus(0);
        } else {
            //快递员
            msg.setStatus(1);
        }
        msg.setResult(wxUser.getPhone());
        msg.setData(userService.findByPhone(wxUser.getPhone()));

        return JSONUtil.toJSON(msg);
    }


}
